import os
import sys
import tempfile
import copy
import re
from .sfprops import *
from subprocess import *

log = []

class session:
    def __init__(self, process, mode):
        self.mode = mode
        self.program = process.program # cdp_program instance
        self.process = copy.deepcopy(self.program.processes[process.name]) # cdp_program instance

        if mode and self.process.modes:
            if self.process.modes[mode]:
                self.process.set_mode(mode)
            else:
                raise ValueError("mode %d does not exist for %s %s" % (mode, program, process))

        self.parameters = self.process.parameters
        self.params = self.process.params

        print(self.process.params)


    def __setattr__(self, name, value):
        if "params" in self.__dict__ and self.params:
            if name in self.params or "-" + name in self.params:
                if "-" + name in self.params:
                    name = "-" + name
                self.params[name].value = value
                return True
        self.__dict__[name] = value

    def check_parameters(self):
        for parameter in self.parameters:
            if parameter:
                try:
                    #parameter.check()
                    return True
                except:
                    raise
        return True

    def set_value(self, param, value):
        self.params[param].value = value

    def queue(self, input_files):
        print("queue mode {}".format(self.mode))
        out = []

        self.check_parameters()

        for input_file in input_files:
            if self.process.description:
                print(( "Process:", self.process.description))
            if self.mode and (self.process.modes[self.mode] and self.process.modes[self.mode].description):
                print(( "Mode: %s" % self.process.modes[self.mode].description))


            if os.path.exists(input_file):
                queue = []
            else:
                raise ValueError("can't find %s" % input_file)

            sfp = sfprops(input_file).props

            print("mode: {}\n".format(self.mode))

            if self.mode and self.process.modes and self.mode in self.process.modes:
                m = self.process.modes[self.mode]
            else:
                m = None

            queue += [self.program.name, self.process.name]

            self.validate_io(m, sfp)

            if self.mode:
                queue.append(str(self.mode))

            queue.append(input_file)

            if m and m.output_filename == "analfile":
                ext = "ana"
            else:
                ext = "wav"

            output_filename = ("%s%s%s.%s" % (input_file,
                                              self.program.name[2:6],
                                              self.process.name[2:6],
                                              ext)
                              )

            if os.path.exists(output_filename):
                os.unlink(output_filename)

            queue.append(output_filename)


            for parameter in self.parameters:
                if parameter is not None and parameter[0][0] in self.params.keys():
                    queue += "-" + str(parameter[0][0])
                    queue += str(self.params[parameter[0][0]])

            print(" ".join(queue))

            """GOGOGOGOGOGOGOGOGOGOGO
            """
            po = Popen(queue, shell = True, stdout = PIPE, stderr = PIPE)

            ret = po.communicate()[0]

            print(("po.communicate()[0] = %s\n" % ret[0]))

            if ret[0]:
                """ FAIL - PUT ORIGINAL FILE BACK
                """
                rename = "mv %s %s" % (input_file, output_filename)
                print("moving file back: {} {} {}".format(rename, output_filename, ret),)
                print(("%s %d" % (rename, call(rename))),)
                out += output_filename

            out += output_filename

        return out

    def validate_io(self, m, sfp):
        if sfp["file_type"] is "soundfile":
            if m.input_type in ["-", "S", "M", "sndfile"] :
                if m.input_type is "M" and int(sfp["channels"]) is not 1:
                    raise ValueError("ERROR: Process requires mono file.")
                elif m.input_type is "S" and int(sfp["channels"]) is not 2:
                    raise ValueError("ERROR: Process requires stereo file.")

            if m.input_type in ["-", "S", "M", "sndfile"] and sfp["file_type"] is not "soundfile":
                raise ValueError("ERROR: Process requires a soundfile. This is a \"%s\"." % sfp["file_type"])

            if m.input_type == "analfile" and "analysis" not in sfp["file_type"]:
                raise ValueError("ERROR: Process requires an analysis file. This is a \"%s\"." % sfp["file_type"])
